﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DistanceLearning.Filters;
using DistanceLearning.Models;

namespace DistanceLearning.Controllers
{
    [Authorize(Roles = JournalStatic.AdminRole)]
    [InitializeSimpleMembership]
    public class SettingsController : JournalBaseController
    {
        public SettingsController()
        {
            if (!Roles.RoleExists(JournalStatic.AdminRole))
                Roles.CreateRole(JournalStatic.AdminRole);
            if (!Roles.RoleExists(JournalStatic.SchoolAdminRole))
                Roles.CreateRole(JournalStatic.SchoolAdminRole);
        }

        public ActionResult Index()
        {
            var schools = CreateSchoolDetails(UsersContext.Schools);
            ViewBag.SchoolList = schools;
            ViewBag.UserProfiles = UsersContext.UserProfiles.ToList();
            ViewBag.SchoolAdminProfiles = GetSchoolAdminProfiles();
            return View();
        }

        public ViewResult AddNewSchool()
        {
            //var schools = UsersContext.Schools;
            //var schoolsDetails = CreateSchoolDetails(schools);
            //return PartialView("_SchoolList", schoolsDetails);
            return View();
        }

        [HttpPost]
        public RedirectToRouteResult AddNewSchool(School school)
        {
            UsersContext.Schools.InsertOnSubmit(school);
            UsersContext.SubmitChanges();

            ViewBag.SchoolList = CreateSchoolDetails(UsersContext.Schools);
            return RedirectToAction("Index", "Settings");
        }

        public ViewResult DeleteSchool(int id)
        {
            var schools = UsersContext.Schools;
            var schoolToDelete = schools.FirstOrDefault(s => s.SchoolId == id);
            if (schoolToDelete != null)
            {
                UsersContext.Schools.DeleteOnSubmit(schoolToDelete);
                UsersContext.SubmitChanges();
            }

            //var schoolsDetails = CreateSchoolDetails(schools);
            //return View("_SchoolList", schoolsDetails);

            ViewBag.SchoolList = CreateSchoolDetails(UsersContext.Schools);
            return View("Index");
        }

        public ViewResult EditSchool(int id)
        {
            var school = UsersContext.Schools.First(s => s.SchoolId == id);
            return View(school);
        }

        [HttpPost]
        public RedirectToRouteResult EditSchool(School newSchool)
        {
            var schoolToUpdate = UsersContext.Schools.First(id => id.SchoolId == newSchool.SchoolId);
            schoolToUpdate.SchoolName = newSchool.SchoolName;
            schoolToUpdate.Details = newSchool.Details;
            UsersContext.SubmitChanges();

            return RedirectToAction("Index", "Settings");
        }

        public RedirectToRouteResult CreateSchoolDatabase(int id)
        {
            var schools = UsersContext.Schools;
            var school = UsersContext.Schools.First(schoolId => schoolId.SchoolId == id);
            using (var schoolDb = new JournalContext(ConnectionHelper.GetSchoolConnection(school.SchoolId)))
            {
                if (!schoolDb.DatabaseExists())
                    schoolDb.CreateDatabase();
                schoolDb.SubmitChanges();
            }

            return RedirectToAction("Index", "Settings");
        }

        private bool ExistSchoolDatabase(int schoolId)
        {
            var school = UsersContext.Schools.First(s => s.SchoolId == schoolId);
            using (var journalContext = new JournalContext(ConnectionHelper.GetSchoolConnection(school.SchoolId)))
            {
                return journalContext.DatabaseExists();
            }
        }
 
        private IEnumerable<SchoolDetails> CreateSchoolDetails(IEnumerable<School> schools)
        {
            var details = schools.Select(s => new SchoolDetails
                                                  {
                                                      SchoolId = s.SchoolId,
                                                      SchoolName = s.SchoolName,
                                                      Details = s.Details,
                                                      HaveDatabase = ExistSchoolDatabase(s.SchoolId),
                                                  }).ToList();
            return details;
        }

        [HttpPost]
        public ActionResult AddUserToRole(int userProfileId)
        {
            var userProfile = UsersContext.UserProfiles.First(profile => profile.UserId == userProfileId);

            if (!Roles.IsUserInRole(userProfile.UserName, JournalStatic.SchoolAdminRole))
                Roles.AddUserToRole(userProfile.UserName, JournalStatic.SchoolAdminRole);

            var allAdminProfiles = GetSchoolAdminProfiles();
            return PartialView("_UserProfiles", allAdminProfiles);
        }

        private IEnumerable<UserProfile> GetSchoolAdminProfiles()
        {
            return UsersContext.UserProfiles.ToList()
                .Where(p => Roles.IsUserInRole(p.UserName, JournalStatic.SchoolAdminRole))
                .Select(p => p).ToList();
        }
    }
}
